package controllers;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import play.mvc.Call;
import play.mvc.Controller;
import play.mvc.Result;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class BaseController extends Controller {


    public static String payload() {
        byte[] bytes = request().body().asRaw().asBytes();
        return new String(bytes);
    }

    public static String getParam(String name) {
        Map<String, String[]> params = request().queryString();
        if (!params.containsKey(name)) {
            return null;
        }
        String[] values = params.get(name);
        if (values.length < 1) {
            return null;
        }
        return values[0];
    }

    public static boolean getBoolParam(String name, boolean defaultValue) {
        String v = getParam(name);
        if (v == null) {
            return defaultValue;
        }
        try {
            return Boolean.valueOf(v);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static String[] getParamArray(String name) {
        Map<String, String[]> params = request().queryString();
        if (!params.containsKey(name)) {
            return null;
        }
        String[] values = params.get(name);
        return values;
    }

    public static String[] getPostParamArray(String name) {
        Map<String, String[]> params = request().body().asFormUrlEncoded();
        if (!params.containsKey(name)) {
            return null;
        }
        String[] values = params.get(name);
        return values;
    }

    public static String getPostParam(String name) {
        Map<String, String[]> params = request().body().asFormUrlEncoded();
        if (!params.containsKey(name)) {
            return null;
        }
        String[] values = params.get(name);
        if (values.length < 1) {
            return null;
        }
        return values[0];
    }

    public static Boolean getBoolPostParam(String name) {
        String value = getPostParam(name);
        if (value == null) {
            return null;
        }
        return Boolean.valueOf(value);
    }

    public static int[] getIntPostParamArray(String name, int[] defaultValue) {
        String[] strValueArray = getPostParamArray(name);
        if (strValueArray == null) {
            return defaultValue;
        }
        List<Integer> resultList = new ArrayList<Integer>();
        for (String s : strValueArray) {
            try {
                resultList.add(Integer.valueOf(s));
            } catch (Exception e) {
            }
        }
        int[] result = new int[resultList.size()];
        for (int i = 0; i < resultList.size(); ++i) {
            result[i] = resultList.get(i);
        }
        return result;
    }

    public static Integer getIntPostParam(String name) {
        String value = getPostParam(name);
        if (value == null) {
            return null;
        }
        try {
            return Integer.valueOf(value);
        } catch (Exception e) {
            return null;
        }
    }

    public static Long getLongPostParam(String name) {
        String value = getPostParam(name);
        if (value == null) {
            return null;
        }
        try {
            return Long.valueOf(value);
        } catch (Exception e) {
            return null;
        }
    }

    public static Map<String, String[]> getPostData() {
        return request().body().asFormUrlEncoded();
    }

    public static Integer getIntParam(String name) {
        String value = getParam(name)/*.substring(0,2)*/;//用于在文章的URL里加了其他的内容，所以在提取article_id参数值时要对字符串进行截取，用于文章的id是两位数字，所以窃取0-2的字符

        if (value == null) {
            return null;
        }
        return Integer.valueOf(value);
    }

    public static Integer getIntParam(String name, int defaultValue) {
        Integer val = getIntParam(name);
        return val != null ? val : defaultValue;
    }

    public static int[] getIntParamArray(String name, int[] defaultValue) {
        String[] a1 = request().queryString().get(name);
        if (a1 == null) {
            return defaultValue;
        }
        int[] result = new int[a1.length];
        for (int i = 0; i < a1.length; ++i) {
            result[i] = Integer.valueOf(a1[i]);
        }
        return result;
    }

    public static String getNotEmptyParam(String name, String defaultValue) {
        String val = getParam(name);
        if (val != null && val.trim().length() > 0) {
            return val;
        } else {
            return defaultValue;
        }
    }

    public static String getParam(String name, String defaultValue) {
        String val = getParam(name);
        return val != null ? val : defaultValue;
    }

    public static Integer getIntPostParam(String name, int defaultValue) {
        Integer val = getIntPostParam(name);
        return val != null ? val : defaultValue;
    }

    public static String getPostParam(String name, String defaultValue) {
        String val = getPostParam(name);
        return val != null ? val : defaultValue;
    }

    public static Result ajaxResult(boolean success, Object value) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", success);
        jsonObject.put("data", value);
        return ok(jsonObject.toJSONString());
    }

    public static Result ajaxResult(boolean success, Object value, int customInt) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", success);
        jsonObject.put("data", value);
        jsonObject.put("customInt", customInt);
        return ok(JSONObject.toJSONString(jsonObject, SerializerFeature.DisableCircularReferenceDetect));
    }

    public static Result ajaxResult(boolean success, Object value, boolean isDisableCircularReferenceDetect) {
        if (isDisableCircularReferenceDetect == true) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("success", success);
            jsonObject.put("data", value);
            return ok(JSONObject.toJSONString(jsonObject, SerializerFeature.DisableCircularReferenceDetect));
        } else return ok("error");
    }

    public static Result ajaxResult(boolean success, Object value, boolean isDisableCircularReferenceDetect, int customInt) {
        if (isDisableCircularReferenceDetect == true) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("success", success);
            jsonObject.put("data", value);
            jsonObject.put("customInt", customInt);
            return ok(JSONObject.toJSONString(jsonObject, SerializerFeature.DisableCircularReferenceDetect));
        } else return ok("error");
    }

    public static Result ajaxResult(boolean success, Object value, boolean isDisableCircularReferenceDetect, int customInt, Boolean refresh) {
        if (isDisableCircularReferenceDetect == true) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("success", success);
            jsonObject.put("data", value);
            jsonObject.put("customInt", customInt);
            jsonObject.put("refresh", refresh);
//            return ok(jsonObject.toJSONString());
            return ok(JSONObject.toJSONString(jsonObject, SerializerFeature.DisableCircularReferenceDetect));
        } else return ok("error");
    }


    public static Result ajaxResultForCircle(boolean success, Object value) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", success);
        jsonObject.put("data", value);
        SerializerFeature feature = SerializerFeature.DisableCircularReferenceDetect;
        return ok(JSON.toJSONString(jsonObject, SerializerFeature.DisableCircularReferenceDetect));
    }


    public static Result ajaxSuccessForCircle(Object value) {
        return ajaxResultForCircle(true, value);
    }

    public static Result ajaxSuccess(Object value) {
        return ajaxResult(true, value);
    }

    public static Result ajaxSuccess(Object value, int customInt) {
        return ajaxResult(true, value, customInt);
    }

    public static Result ajaxSuccess(Object value, boolean isDisableCircularReferenceDetect) {
        return ajaxResult(true, value, isDisableCircularReferenceDetect);
    }

    public static Result ajaxSuccess(Object value, boolean isDisableCircularReferenceDetect, int customInt) {
        return ajaxResult(true, value, isDisableCircularReferenceDetect, customInt);
    }

    public static Result ajaxSuccess(Object value, boolean isDisableCircularReferenceDetect, int customInt, Boolean refresh) {
        return ajaxResult(true, value, isDisableCircularReferenceDetect, customInt, refresh);
    }

    public static Result ajaxException(Exception e) {
        return ajaxFail(e.getMessage());
    }

    public static Result ajaxFail(Object value) {
        return ajaxResult(false, value);
    }

    //记录用户登录信息，用于多个终端，只能一个登录
//    public static Map<String , String>LoginUserMap = new HashMap<String, String>();



    public static boolean isAjaxRequest(play.mvc.Http.Request request) {
        String header = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equals(header);
    }

    /**
     * 重定向到a或b中不为空的值，优先考虑a
     */
    protected static Result redirectAOrB(String a, Call b) {
        if (a != null) {
            return redirect(a);
        } else {
            return redirect(b);
        }
    }

    //注：ajaxSuccess() 返回的是“Content-Type: text/plain”，不是json数据
    public static Result okJson(boolean success, String message, Object data) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", success);
        jsonObject.put("message", message);
        jsonObject.put("data", data);
        return ok(jsonObject.toJSONString()).as("json/application");
    }
}